<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { ElMessage } from 'element-plus'
import { Check, Close, Delete } from '@element-plus/icons-vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStore } from '@/store/modules/locale'
import { getZhHKAndPinyin, getZhCNAndPinyin } from '@/api/common'
import { selectModule, saveDictionary, getDictionary, checkDictKey } from '@/api/develop'

defineOptions({
  name: 'DataDictEdit'
})

const localeStore = useLocaleStore()

const { t } = useI18n()
const { emitter } = useEmitt()
const formRef = ref()
const { currentRoute } = useRouter()

const state = reactive({
  // 表单数据
  formData: {
    dicId: null,
    dicKey: '',
    moduleId: '',
    enName: '',
    hkName: '',
    dicName: '',
    sortNo: 1,
    isFixed: 0,
    status: 1,
    seq: 1
  },
  details: [],
  deleteIds: [],

  // 校验规则
  formRules: {
    dicKey: [
      {
        required: true,
        message: t('dataDict.key') + t('common.notEmpty'),
        trigger: ['blur']
      }
    ],
    dicName: [
      {
        required: true,
        message: t('dataDict.name') + t('common.notEmpty'),
        trigger: ['blur']
      }
    ],
    hkName: [
      {
        required: true,
        message: t('common.hkName') + t('common.notEmpty'),
        trigger: ['blur']
      }
    ],
    enName: [
      {
        required: true,
        message: t('common.enName') + t('common.notEmpty'),
        trigger: ['blur']
      }
    ],
    moduleId: [
      {
        required: true,
        message: t('orderNo.module') + t('common.notEmpty'),
        trigger: ['blur', 'change']
      }
    ]
  },
  modNameField: 'moduleName',
  moduleList: [{}],
  loading: false
})

//加载事件
onMounted(async () => {
  state.moduleList = await selectModule()
  state.details = []
  //当前语言
  const curLang = localeStore.getCurrentLocale.lang
  if (curLang == 'en') {
    state.modNameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.modNameField = 'hkName'
  }
  init()
})

//删除下拉项记录
const deleteRow = (id, index) => {
  if (id && id.length > 0) {
    state.deleteIds.push(id)
  }
  state.details.splice(index, 1)
}
//新增下拉项记录
const addRow = () => {
  const row = {
    sortNo: state.details.length + 1,
    isFixed: 0,
    seq: 1,
    status: 1,
    valId: null,
    saveVal: '',
    showText: '',
    hkText: '',
    enText: ''
  }
  state.details.push(row)
}

// 保存表单
const save = () => {
  formRef.value.validate(async (vaild) => {
    if (!vaild) {
      return
    }
    let form = Object.assign({}, state.formData)
    //校验明细记录
    if (state.details && state.details.length > 0) {
      for (const row of state.details) {
        if (row.showText == '' || row.saveVal == '') {
          ElMessage.warning(t('dataDict.rowCheck'))
          return
        }
      }
    }
    if (checkDetails()) {
      return
    }
    let deleteIds = ''
    if (state.deleteIds && state.deleteIds.length > 0) {
      deleteIds = state.deleteIds.join(',')
    }
    let data = { master: form, details: [...state.details], deleteIds: deleteIds }
    state.loading = true
    let type = 'add'
    if (form.dicId) {
      type = 'edit'
    }
    await saveDictionary(data).then((res) => {
      const result = res as any
      //保存成功
      if (result.success) {
        //刷新列表
        emitter.emit('refreshDictionaryList', type)
        goBack()
      } else {
        ElMessage.error(t(result.message))
      }
      state.loading = false
    })
  })
}

//检查子表关键列是否有重复
const checkDetails = () => {
  if (state.details.length == 0) {
    return false
  }
  const len = state.details.length
  const vals = new Set()
  const texts = new Set()
  for (const detail of state.details) {
    const row = detail as any
    vals.add(row.saveVal)
    texts.add(row.showText)
  }
  if (vals.size != len) {
    ElMessage.error(t('dataDict.valRepeat'))
    return true
  }
  if (texts.size != len) {
    ElMessage.error(t('dataDict.textRepeat'))
    return true
  }
  return false
}

//检查Key是否重复
const checkKey = (event) => {
  const key = event.target.value
  if (!key || key.length == 0) {
    return
  }
  checkDictKey(key, state.formData.dicId)
}
// 返回列表
const goBack = () => {
  emitter.emit('closeTag', {
    closePath: currentRoute.value.fullPath,
    backPath: '/Develop/DataDictionary'
  })
}
/**
 * @description 当繁体中文为空时，转换简体中文为繁体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhHKAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //繁体中文为空时才自动转换
  if (state.formData.hkName.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  state.formData.hkName = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
  if (state.formData.dicKey.length == 0) {
    state.formData.dicKey = data.data.pinyin.replace(/\s+/g, '')
  }
  formRef.value.clearValidate(['hkName', 'dicKey', 'enName'])
}

/**
 * 子表输入简体中文后的事件
 * @param event 事件
 * @param row 当前行记录
 */
const inputCnText = async (event, row) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  if (row.hkText.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  row.hkText = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (row.enText.length == 0) {
    row.enText = data.data.pinyin
  }
}

/**
 * 子表输入繁体中文后的事件
 * @param event 事件
 * @param row 当前行记录
 */
const inputHkText = async (event, row) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  if (row.showText.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  row.showText = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (row.enText.length == 0) {
    row.enText = data.data.pinyin
  }
}

/**
 * @description 当简体中文为空时，转换繁体中文为简体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhCNAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //简体中文为空时才自动转换
  if (state.formData.dicName.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  state.formData.dicName = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
  if (state.formData.dicKey.length == 0) {
    state.formData.dicKey = data.data.pinyin.replace(/\s+/g, '')
  }
  formRef.value.clearValidate(['dicName', 'dicKey', 'enName'])
}

//渲染页面的接口
const init = async () => {
  const id = currentRoute.value.query.id as string
  //修改
  if (id) {
    const data = (await getDictionary(id)) as any
    state.formData = data.data.master
    state.details = data.data.details
  } else {
    addRow()
    const moduleId = currentRoute.value.query.moduleId as string
    if (moduleId) {
      state.formData.moduleId = moduleId
    }
  }
}
</script>

<template>
  <div>
    <!-- 卡片表頭 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ $t('dataDict.dict') }}</span>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="state.formData"
        :rules="state.formRules"
        class="demo-form-inline"
        label-position="left"
        label-width="150px"
        style="padding-top: 10px"
      >
        <el-row :gutter="40">
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('orderNo.module')" prop="moduleId">
              <el-select
                v-model="state.formData.moduleId"
                :placeholder="$t('common.selectText')"
                size="default"
                :disabled="state.formData.isFixed == 1"
              >
                <el-option
                  v-for="item in state.moduleList"
                  :key="item.moduleId"
                  :label="item[state.modNameField]"
                  :value="item.moduleId"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('dataDict.name')" prop="dicName">
              <el-input
                v-model="state.formData.dicName"
                :placeholder="$t('common.inputText') + $t('dataDict.name')"
                maxlength="50"
                show-word-limit
                :disabled="state.formData.isFixed == 1"
                @blur="zhHKAndPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.hkName')" prop="hkName">
              <el-input
                v-model="state.formData.hkName"
                :placeholder="$t('common.inputText') + $t('common.hkName')"
                maxlength="50"
                show-word-limit
                :disabled="state.formData.isFixed == 1"
                @blur="zhCNAndPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.enName')" prop="enName">
              <el-input
                v-model="state.formData.enName"
                :placeholder="$t('common.inputText') + $t('common.enName')"
                maxlength="50"
                show-word-limit
                :disabled="state.formData.isFixed == 1"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('dataDict.key')" prop="dicKey">
              <el-input
                v-model="state.formData.dicKey"
                :placeholder="$t('common.inputText') + $t('dataDict.key')"
                maxlength="50"
                show-word-limit
                @blur="checkKey($event)"
                :disabled="state.formData.isFixed == 1"
              />
            </el-form-item>
            <el-form-item :label="$t('common.status')" prop="status">
              <el-switch
                v-model.number="state.formData.status"
                :active-value="1"
                :inactive-value="0"
                :disabled="state.formData.isFixed == 1"
              />
            </el-form-item>
            <el-form-item :label="$t('common.sort')" prop="sort">
              <el-input-number
                :min="1"
                :max="999999"
                :step="10"
                v-model="state.formData.sortNo"
                :placeholder="$t('common.inputText') + $t('common.sort')"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin: 10px 0; text-align: right">
        <el-button
          type="success"
          size="small"
          plain
          @click="addRow()"
          v-if="state.formData.isFixed != 1"
        >
          <Icon icon="material-symbols:add-circle-rounded" />
          <span>{{ t('dataDict.addNew') }}</span></el-button
        >
      </div>
      <div style="width: 100%">
        <el-table
          :data="state.details"
          tooltip-effect="light"
          style="width: 100%; border-color: #a0cfff; font-size: 12px"
          stripe
          default-expand-all
          border
          :header-cell-style="{
            background: 'var(--el-color-primary-light-9)',
            color: '#409eff'
          }"
        >
          <el-table-column type="index" min-width="60">
            <template #header>
              <div style="margin-bottom: -10px">
                <Icon
                  icon="ant-design:field-number-outlined"
                  size="24"
                  :title="$t('common.number')"
              /></div>
            </template>
          </el-table-column>
          <el-table-column prop="saveVal" :label="$t('dataDict.saveVal')" min-width="120">
            <template #default="scope">
              <span class="required">*</span>
              <el-input
                v-model="scope.row.saveVal"
                class="inputRequired"
                :maxlength="50"
                :disabled="scope.row.isFixed == 1"
              />
            </template>
          </el-table-column>
          <el-table-column prop="showText" :label="$t('dataDict.showText')" min-width="120">
            <template #default="scope">
              <span class="required">*</span>
              <el-input
                v-model="scope.row.showText"
                class="inputRequired"
                :maxlength="50"
                :disabled="scope.row.isFixed == 1"
                @blur="inputCnText($event, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="hkText" :label="$t('dataDict.hkText')" min-width="120">
            <template #default="scope">
              <el-input
                v-model="scope.row.hkText"
                :disabled="scope.row.isFixed == 1"
                :maxlength="50"
                @blur="inputHkText($event, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="enText" :label="$t('dataDict.enText')" min-width="120">
            <template #default="scope">
              <el-input
                v-model="scope.row.enText"
                :disabled="scope.row.isFixed == 1"
                :maxlength="50"
              />
            </template>
          </el-table-column>
          <el-table-column prop="sortNo" :label="$t('common.sort')" min-width="120">
            <template #default="scope">
              <el-input v-model="scope.row.sortNo" :maxlength="9" />
            </template>
          </el-table-column>
          <el-table-column prop="status" :label="$t('common.status')" width="80">
            <template #default="scope">
              <el-switch
                v-model.number="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                :disabled="scope.row.isFixed == 1"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="op"
            align="center"
            fixed="right"
            :label="$t('common.operation')"
            width="80"
          >
            <template #default="scope">
              <el-button
                type="danger"
                size="small"
                plain
                circle
                :title="$t('common.delete')"
                v-if="scope.row.isFixed != 1"
                @click="deleteRow(scope.row.valId, scope.$index)"
              >
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="detailFooter" v-if="state.formData.isFixed != 1">
        <el-button type="primary" plain @click="save" :loading="state.loading">
          <el-icon><Check /></el-icon>&nbsp;{{ $t('common.save') }}
        </el-button>
        <el-button type="info" plain @click="goBack">
          <el-icon><Close /></el-icon>&nbsp;{{ $t('common.giveUp') }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>
<style lang="less" scoped>
.box-card {
  .card-header {
    font-size: 16px;
    letter-spacing: 1px;
  }
  :deep(.el-input) {
    font-size: 12px;
  }
  :deep(.el-textarea__inner) {
    height: 85px;
    font-size: 12px;
  }
}
:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
}
.el-select-dropdown__item {
  font-size: 12px;
}
.required {
  color: red;
}
.inputRequired {
  width: 90%;
  margin-left: 3px;
}
</style>
